#!/usr/bin/env python3 
# -*- coding: utf-8 -*-
# @Author  : Grit<dooms21day@163.com>
# @Company : 成都慧创智通信息技术有限公司
# @Brand   : 企慧蚁
# @Copyright: 2021-

from odoo import api, fields, models


class GeneralReportWizard(models.Model):
    _name = "general.report.wizard"
    _description = "报告查询"

    name = fields.Char("查询报告", compute="_compute_name")
    date_start = fields.Datetime("开始日期", required=True)
    date_end = fields.Datetime("截止日期", required=True)
    company_id = fields.Many2one("res.company", "公司")
    type = fields.Selection([
        ("transfer", "收发存"),
        ("turnover", "周转率"),
    ], string="类型", required=True)
    user_id = fields.Many2one("res.users", "查询用户", default=lambda self: self.env.user.id, readonly=True)

    transfer_ids = fields.One2many("stock.transfer.detail.report", "wizard_id", "收发存明细")
    turnover_ids = fields.One2many("stock.turnover.report", "wizard_id", "周转率明细")

    @api.depends("type", "date_start", "date_end")
    def _compute_name(self):
        for record in self:
            record.name = f"{record.type}({record.date_start}-{record.date_end})"

    @api.onchange("date_start")
    def _onchange_date_start(self):
        if self.date_start and (not self.date_end or self.date_start > self.date_end):
            self.date_end = self.date_start

    def open_transfers(self):
        """
        打开收发存记录
        :return:
        """
        action = {
            "name": "收发存报表",
            "type": "ir.actions.act_window",
            "view_mode": "tree",
            "res_model": "stock.transfer.detail.report",
            "domain": [('wizard_id', '=', self.id)]
        }
        return action

    def open_turnovers(self):
        """
        打开周转率记录
        :return:
        """
        action = {
            "name": "周转率报表",
            "type": "ir.actions.act_window",
            "view_mode": "tree",
            "res_model": "stock.turnover.report",
            "domain": [('wizard_id', '=', self.id)]
        }
        return action

    def action_done(self, context):
        self.ensure_one()
        is_recompute = context.get("is_recompute", False) or self.env.context.get("is_recompute", False)
        if is_recompute:
            to_delete_fields = ['transfer_ids', 'turnover_ids']
            for delete_field in to_delete_fields:
                self[delete_field].unlink()

        # 已存在的报告查询的记录，如果有的话，默认直接返回之前已查询的记录
        exist_domain = [
            ("id", "!=", self.id),
            ('date_start', '=', self.date_start),
            ('date_end', '=', self.date_end),
            ('type', '=', self.type),
        ]
        if self.company_id:
            exist_domain += [('company_id', '=', self.company_id.id)]
        exist_wizard = self.search(exist_domain, limit=1, order="create_date desc")

        # 计算完成后直接跳转到获得的报表明细数据列表
        action = {
            "type": "ir.actions.act_window",
            "view_mode": "tree",
        }
        if exist_wizard:
            wizard_id = exist_wizard.id
        else:
            wizard_id = self.id
            # 准备计算报表的筛选domain，用于筛选报表的基础数据
            domain = [
                ('date', '<', self.date_end)
            ]
            if self.company_id:
                domain += [('company_id', '=', self.company_id.id)]

            if self.type == "transfer":
                self.env['stock.transfer.detail.report'].compute_report_data(
                    self.date_start, self.date_end, domain, wizard_id
                )
                action.update(
                    name="收发存报表",
                    res_model="stock.transfer.detail.report"
                )
            elif self.type == 'turnover':
                self.env['stock.turnover.report'].compute_report_data(
                    self.date_start, self.date_end, domain, wizard_id
                )
                action.update(
                    name="库存周转率报表",
                    res_model="stock.turnover.report"
                )
        action.update(domain=[('wizard_id', '=', wizard_id)])
        return action
